package com.itcast.clientx.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Component
public class Client {

    private PoolingHttpClientConnectionManager manager;
    @Autowired
    private TextUtil util;

    public Client() {
        this.manager = new PoolingHttpClientConnectionManager();
        manager.setMaxTotal(100);
        /**
         * 设置主机连接数
         * 同一个域名的连接数限制
         * 避免其他域名没有连接可用
         */
        manager.setDefaultMaxPerRoute(10);
    }

    /**
     * 获取HTML数据
     * @param url
     * @return
     */
    public String getHTML(String url,String cookie) {
        CookieStore store = new BasicCookieStore();
        CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).setConnectionManager(manager).build();


        CloseableHttpResponse response = null;
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(500).setSocketTimeout(10*1000).build();

        try {

            BasicClientCookie cookie1 = new BasicClientCookie("","");
            HttpGet request = new HttpGet(url);
            request.setHeader("cookie",cookie);
            request.setHeader("Referrer Policy","no-referrer-when-downgrade");
            request.setHeader("Remote Address","172.67.70.218:443");

            request.setHeader("referer","https://mvnrepository.com/search?q=hibernate");
            request.setHeader("upgrade-insecure-requests","1");

            request.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3868.400 QQBrowser/10.8.4394.400");

            request.setConfig(config);
            response = client.execute(request);

            int status = response.getStatusLine().getStatusCode();
            System.out.println("status==  "+status);
            if(status == 200){
                HttpEntity entity = response.getEntity();
                if(entity == null){
                    return null;
                }
                String string = EntityUtils.toString(entity, "utf8");

                return string;
            }
            if(status == 404){
                return "404";
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.shutdown(response);

        }
        return null;
    }
    public String downloadimg(String url) {
        System.out.println("downloadimg== "+url);
        if(url.length()<10){
            return null;
        }

        CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();


        CloseableHttpResponse response = null;
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(500).setSocketTimeout(10*1000).build();

        try {

            HttpGet get = new HttpGet(url);
            /*
            get.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3868.400 QQBrowser/10.8.4394.400");
            */
            get.setConfig(config);
            response = client.execute(get);
            int status = response.getStatusLine().getStatusCode();
            System.out.println("status==  "+status);
            if(status == 200){
                HttpEntity entity = response.getEntity();
                if(entity == null){
                    return null;
                }

                /**
                 * 后缀名称
                 */
                String suffix = util.suffix(url);
                /**
                 * 文件名
                 */
                suffix = UUID.randomUUID()+""+suffix;
                FileOutputStream stream = new FileOutputStream("D:/github/test/"+suffix);
                entity.writeTo(stream);

                return suffix;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.shutdown(response);

        }
        return null;
    }
    public void shutdown(CloseableHttpResponse response){
        try {
            if(response!=null){
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void testdownload(){
        this.downloadimg("https://img13.360buyimg.com/n7/jfs/t1/143051/26/15747/73035/5fbdd54cE80757a48/67c387e1d0dc5c83.jpg");
    }

    /**
     *
     * @param url
     * @return
     * https://1258712167.vod2.myqcloud.com/fb8e6c92vodtranscq1258712167/7e4ed2515285890813050653699/drm/voddrm.token.dWluPTE2MTM3MTI0MTQ7c2tleT1AVWc5dDVQRVFrO3Bza2V5PWdzOGJwR3FRVXdFM2V2TXpWb0M0cFRraEdoTlFFT3NlOWZGbWNMWExwNHNfO3Bsc2tleT0wMDA0MDAwMGI5ZjZhMTI0MTljOTRiNjRhN2E2YzgyNThlYzkxNTQ1MWMxOTg4ZDc3Y2U3ZWZkZWIyMzgwYjAzYzlmMDAyM2I5MWI0MTNmODA0NGU3MTllO2V4dD07dWlkX3R5cGU9MDt1aWRfb3JpZ2luX3VpZF90eXBlPTA7Y2lkPTIyNjM3MzY7dGVybV9pZD0xMDMyOTk1NzE7dm9kX3R5cGU9MA==.v.f56150.m3u8?exper=0&sign=790c56093240ae569544990077a58f85&t=60cbe6c8&us=1038165738095132733
     */
    public String downloadvideo(String url) {
        System.out.println("downloadimg== "+url);


        CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager).build();


        CloseableHttpResponse response = null;
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(500).setSocketTimeout(1000*1000).build();

        try {

            HttpGet get = new HttpGet(url);
            get.setHeader("Referer","https://ke.qq.com/webcourse/2263736/103299571");
            get.setHeader("Accept","*/*");

            get.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3868.400 QQBrowser/10.8.4394.400");

            get.setConfig(config);
            response = client.execute(get);
            int status = response.getStatusLine().getStatusCode();
            System.out.println("status==  "+status);
            if(status == 200){
                HttpEntity entity = response.getEntity();
                if(entity == null){
                    return null;
                }

                /**
                 * 后缀名称
                 */
                String suffix = util.suffix(url);
                /**
                 * 文件名
                 */
                suffix = UUID.randomUUID()+""+suffix;
                suffix = "v.f30739.ts";
                FileOutputStream stream = new FileOutputStream("D:/github/test/"+suffix);
                entity.writeTo(stream);

                return suffix;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.shutdown(response);

        }
        return null;
    }

}
